package com.tjl.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.tjl.model.Star;
import com.tjl.service.Impl.StarServiceImpl;
import com.tjl.util.CodeMsg;
import com.tjl.util.JwtUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author TJL
 * @date 2022/5/27
 */
@RestController
@RequestMapping("/stars")
public class StarController {

    @Autowired
    private StarServiceImpl service;

    @Autowired
    private JwtUtils jwtUtils;

    @GetMapping
    public CodeMsg getAll(@RequestHeader String token){
        Claims claims = null;
        try {
            claims = jwtUtils.parseJwt(token);
        } catch (Exception e) {
            e.printStackTrace();
            return new CodeMsg(202,"token异常");
        }
        QueryWrapper<Star> wrapper = new QueryWrapper<>();
        wrapper.like("uid",claims.getId());

        return new CodeMsg(service.selectStar(Integer.parseInt(claims.getId())));
    }

    @GetMapping("/{id}")
    public CodeMsg getOne(@PathVariable Integer id,@RequestHeader String token){
        Claims claims = null;
        try {
            claims = jwtUtils.parseJwt(token);
        } catch (Exception e) {
            e.printStackTrace();
            return new CodeMsg(202,"false");
        }

        QueryWrapper<Star> wrapper = new QueryWrapper<>();
        wrapper.like("uid",claims.getId());
        wrapper.like("cid",id);
        List<Star> list = service.list(wrapper);

        if (list.size() >= 1){
            return new CodeMsg(list);
        }
        return new CodeMsg(false);

    }
    
    @PostMapping
    public CodeMsg add(@RequestBody Star star,@RequestHeader String token){
        Claims claims = null;
        try {
            claims = jwtUtils.parseJwt(token);
        } catch (Exception e) {
            e.printStackTrace();
            return new CodeMsg(202,"token异常");
        }
        star.setUid(Integer.parseInt(claims.getId()));
        return new CodeMsg(service.save(star));
    }

    @DeleteMapping("/{id}")
    public CodeMsg delete(@PathVariable Integer id , @RequestHeader String token){
        Claims claims = null;
        try {
            claims = jwtUtils.parseJwt(token);
        } catch (Exception e) {
            e.printStackTrace();
            return new CodeMsg(202,"token异常");
        }
        return new CodeMsg(service.removeById(id));
    }
}
